package com.qd.common.sys.domain.tree;

import com.qd.common.sys.domain.entity.meun.MenuDTO;
import com.qd.common.sys.domain.entity.org.OrgDTO;
import com.qd.common.sys.domain.entity.role.RoleDTO;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * TreeSelect树结构实体类
 *
 * @author sjk
 */
@Data
@Accessors(chain = true)
public class TreeSelect {

    /**
     * 节点ID
     */
    private String id;

    /**
     * 节点名称
     */
    private String name;
    /**
     * 节点层级
     */
//    @JsonIgnore
    private int distance;
    /**
     * 子节点
     */
    private List<TreeSelect> children;


    public TreeSelect(OrgDTO org) {
        this.id = org.getOrgId();
        this.name = org.getOrgName();
        this.distance = org.getDistance();
        if (null != org.getChildren()) {
            this.children = org.getChildren().stream().map(TreeSelect::new).collect(toList());
        }
    }

    public TreeSelect(MenuDTO menu) {
        this.id = menu.getMenuId();
        this.name = menu.getMenuName();
        if (null != menu.getChildren()) {
            this.children = menu.getChildren().stream().map(TreeSelect::new).collect(toList());
        }
    }

    public TreeSelect(RoleDTO roleDTO) {
        this.id = roleDTO.getRoleId();
        this.name = roleDTO.getRoleName();
        if (null != roleDTO.getChildren()) {
            this.children = roleDTO.getChildren().stream().map(TreeSelect::new).collect(toList());
        }
    }

    public Map<String, Object> buildMap() {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>(3);
        map.put("id", this.id);
        map.put("name", this.name);
        if (null != this.children && !this.children.isEmpty()) {
            final List<Map<String, Object>> collect = children.stream()
                    .filter(treeSelect -> treeSelect.getDistance() == 1)
                    .map(treeSelect -> {
                        Map<String, Object> childrenMap = new HashMap<>(3);
                        childrenMap.put("id", treeSelect.id);
                        childrenMap.put("name", treeSelect.name);
                        if (null != treeSelect.getChildren()) {
                            childrenMap.put("children", Collections.emptyList());
                        }
                        return childrenMap;
                    }).collect(toList());

            map.put("children", collect);
        }
        return map;
    }
}
